package com.itheima.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zzw
 * @date 2025/11/15
 * @description 一个bean标签可以有多个property子标签，MutablePropertyValues类用来存储并管理多个PropertyValue对象。
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {

    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        propertyValueList = new ArrayList<>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValues) {
        this.propertyValueList = (propertyValues != null ? propertyValues : new ArrayList<>());
    }

    public PropertyValue[] getPropertyValueList() {
        return this.propertyValueList.toArray(new PropertyValue[0]);
    }

    public PropertyValue getPropertyValue(String propertyName) {
        for (PropertyValue propertyValue : propertyValueList) {
            if (propertyValue.getName().equals(propertyName)) {
                return propertyValue;
            }
        }
        return null;
    }

    // 返回迭代器
    @Override
    public Iterator<PropertyValue> iterator() {
        return this.propertyValueList.iterator();
    }

    public boolean isEmpty() {
        return this.propertyValueList.isEmpty();
    }

    public MutablePropertyValues addPropertyValue(PropertyValue pv) {
        for (int i = 0; i < propertyValueList.size(); i++) {
            PropertyValue currentPv = propertyValueList.get(i);
            if (currentPv.getName().equals(pv.getName())) {
                this.propertyValueList.set(i, new PropertyValue(pv.getName(), pv.getRef(), pv.getRef()));
                return this;
            }
        }
        this.propertyValueList.add(pv);
        return this;
    }

    private boolean contains(String propertyName) {
        return getPropertyValue(propertyName) != null;
    }

}
